from django.contrib.contenttypes.models import ContentType
from django.core.cache import cache
from django.db.models import Q

from apps.system.models import Region
from extensions import serializers
from extensions.common.base import *
from extensions.serializers import *
from extensions.exceptions import *
from apps.pbi.models import *
from apps.system.models import *
from tools.func import get_model_fullname


class CheckFlowSerializer(BaseSerializer):
    class RolesSerializer(BaseSerializer):
        class Meta:
            model = Role
            fields = ['id', 'name']
    check_flow_steps=RolesSerializer(
        source='steps', many=True, read_only=True, label='审批步骤')
    class Meta:
        model = CheckFlow
        fields = ['id', 'name','check_flow_steps']


class ClientSerializer(BaseSerializer):
    company_name = CharField(source='company.name',  read_only=True, label='公司')
    creator_name = CharField(source='creator.name',  read_only=True, label='创建者')
    updater_name = CharField(source='updater.name',  read_only=True, label='更新者')
    client_property_name = CharField(source='client_property.name',  read_only=True, label='客户属性')
    cooperation_methods_items = serializers.SerializerMethodField()
    industry_types_items = serializers.SerializerMethodField()
    region_items = serializers.SerializerMethodField()

    class ClientChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')
        class Meta:
            model = ClientCheck
            fields = ['id', 'client','check_user','check_user_name','opinion','add_time']

    client_checks = ClientChecksSerializer(
        source='ClientChecks_client', many=True, read_only=True, label='审核记录')

    class Meta:
        model = Client
        fields = '__all__'

    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        validated_data['updater'] = self.context['request'].user
        validated_data['company'] = self.context['request'].user.company
        return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updater'] = self.context['request'].user
        return super().update(instance, validated_data)

    def get_cooperation_methods_items(self, obj):
        if not isinstance(obj.cooperation_methods, list):
            return None
        cooperation_methods_names = []
        for id in obj.cooperation_methods:
            name = cache.get(id)
            if name is None:
                try:
                    dict_item = Dict_item.objects.get(id=id)
                    name = dict_item.name
                    cache.set(id, name, 60 * 60 * 24 * 7)
                except Dict_item.DoesNotExist:
                    name = None
            cooperation_methods_names.append(name)
        return '/'.join(cooperation_methods_names)

    def get_industry_types_items(self, obj):
        if not isinstance(obj.industry_types, list):
            return None
        industry_types_names = []
        for id in obj.industry_types:
            name = cache.get(id)
            if name is None:
                try:
                    dict_item = Dict_item.objects.get(id=id)
                    name = dict_item.name
                    cache.set(id, name, 60 * 60 * 24 * 7)  # 缓存 7天
                except Dict_item.DoesNotExist:
                    name = None
            industry_types_names.append(name)

        return '/'.join(industry_types_names)

    def get_region_items(self, obj):
        if not isinstance(obj.region, list):
            return None
        region_names = []
        for id in obj.region:
            name = cache.get(id)
            if name is None:
                try:
                    region_item = Region.objects.get(id=id)
                    name = region_item.region_name
                    cache.set(id, name, 60 * 60 * 24 * 7)  # 缓存 7天
                except Region.DoesNotExist:
                    name = None
            region_names.append(name)

        return '/'.join(region_names)

    # def validate_number(self, value):
    #     # content_type = ContentType.objects.get_for_model(Client)
    #     # models.UserInfo._meta.model_name
    #     # print(get_model_fullname(self.Meta.model))
    #     self.validate_unique({'number': value}, message=f'编号[{value}]已存在')
    #     return value

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value



class SupplierManufactorSerializer(BaseSerializer):
    company_name = CharField(source='company.name',  read_only=True, label='公司')
    filled_by_name = CharField(source='filled_by.name',  read_only=True, label='填报人')
    # class Product_specialtiesSerializer(BaseSerializer):
    #
    #     class Meta:
    #         model = ProductSpecialty
    #         fields = ['id', 'name']

    # product_specialties = Product_specialtiesSerializer(
    #     source='product_specialty', many=True, read_only=True, label='产品覆盖专业')

    class SupplierManufactorChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')
        class Meta:
            model = SupplierManufactorCheck
            fields = ['id', 'supplier_manufactor','check_user','check_user_name','opinion','add_time']

    supplier_manufactor_checks = SupplierManufactorChecksSerializer(
        source='supplier_manufactor_check', many=True, read_only=True, label='审核记录')

    class Meta:
        model = SupplierManufactor
        read_only_fields = ['id']
        fields = ['company','company_name','number', 'name',
                  'accounting_period',
                  'credit_limit',
                  # 'product_specialty',
                  # 'product_specialties',
                  'contact',
                  'filled_by',
                  'filled_by_name',
                  'step','next_checker',
                  'supplier_manufactor_checks',
                  'is_effective','add_time',
                  'phone', 'email',
                  'remark',  *read_only_fields]

    def validate_number(self, value):
        # content_type = ContentType.objects.get_for_model(Client)
        # models.UserInfo._meta.model_name
        # print(get_model_fullname(self.Meta.model))
        self.validate_unique({'number': value}, message=f'编号[{value}]已存在')
        return value

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value

    def create(self, validated_data):
        return super().create(validated_data)

    def update(self, instance, validated_data):
        return super().update(instance, validated_data)


class SupplierIntegratorSerializer(BaseSerializer):
    company_name = CharField(source='company.name',  read_only=True, label='公司')
    filled_by_name = CharField(source='filled_by.name',  read_only=True, label='填报人')

    class SupplierIntegratorChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')
        class Meta:
            model = SupplierIntegratorrCheck
            fields = ['id', 'supplier_integrator','check_user','check_user_name','opinion','add_time']

    supplier_integrator_checks = SupplierIntegratorChecksSerializer(
        source='supplier_integrator_check', many=True, read_only=True, label='审核记录')

    class IntegratorPdfItemSerializer(BaseSerializer):

        class Meta:
            model = SupplierIntegratorPdf
            fields = ['id', 'name', 'file','type']

    integrators_pdf_items = IntegratorPdfItemSerializer(
        source='integrators_pdfs', many=True, read_only=True, label='集成商PDF文件 Item')
    class Meta:
        model = SupplierIntegrator
        read_only_fields = ['id','integrators_pdf_items']
        fields = ['company','company_name','number', 'name',
                  'business_scope',
                  'business_qualification',
                  'contact',
                  'filled_by',
                  'filled_by_name',
                  'step','next_checker',
                  'supplier_integrator_checks',
                  'is_effective','add_time',
                  'phone', 'email',
                  'remark',
                  'integrators_pdfs',
                  *read_only_fields]
        extra_kwargs = {'integrators_pdfs': {'required': False}}

    def validate_number(self, value):
        # content_type = ContentType.objects.get_for_model(Client)
        # models.UserInfo._meta.model_name
        # print(get_model_fullname(self.Meta.model))
        self.validate_unique({'number': value}, message=f'编号[{value}]已存在')
        return value

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value

    def create(self, validated_data):
        return super().create(validated_data)

    def update(self, instance, validated_data):
        return super().update(instance, validated_data)


class ManufactorProductSerializer(BaseSerializer):
    company_name = CharField(source='company.name',  read_only=True, label='公司')
    filled_by_name = CharField(source='filled_by.name',  read_only=True, label='填报人')
    supplier_manufactor_name = CharField(source='supplier_manufactor.name',  read_only=True, label='厂家名称')


    # class ProductSpecialtyItemSerializer(BaseSerializer):
    #
    #     class Meta:
    #         model = ProductSpecialty
    #         fields = ['id', 'name']
    #
    # product_specialties_items = ProductSpecialtyItemSerializer(
    #     source='product_specialty', many=True, read_only=True, label='产品覆盖专业')
    class Meta:
        model = ManufactorProduct
        read_only_fields = ['id']
        fields = ['company','company_name','number', 'name',
                  'product_model',
                  'product_price',
                  'product_specialty',
                  'filled_by',
                  'filled_by_name',
                  'supplier_manufactor','supplier_manufactor_name',
                  # 'product_specialties_items',
                  'add_time',
                  *read_only_fields]

    def validate_number(self, value):
        # content_type = ContentType.objects.get_for_model(Client)
        # models.UserInfo._meta.model_name
        # print(get_model_fullname(self.Meta.model))
        self.validate_unique({'number': value}, message=f'编号[{value}]已存在')
        return value

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value

    def create(self, validated_data):
        return super().create(validated_data)

    def update(self, instance, validated_data):
        return super().update(instance, validated_data)


class IntegratorPdfSerializer(BaseSerializer):

    class Meta:
        model = SupplierIntegratorPdf
        read_only_fields = ['id', 'name','type']
        fields = ['file', *read_only_fields]

    def create(self, validated_data):
        validated_data['name'] = validated_data['file'].name
        validated_data['type'] = self.request.data['type']
        return super().create(validated_data)

class ClientImportExportSerializer(BaseSerializer):
    # company = IntegerField(label='所属公司')
    number = CharField(label='客户编号(必填唯一)')
    name = CharField(label='客户名称(必填唯一)')
    profile = CharField(required=False, label='客户简介')
    cooperation_attribute = JSONField(required=False, label='合作方式，格式：[1,2]')
    cooperation_types = JSONField(required=False, label='合作行业类型，格式：[1,2]')
    contact = CharField(required=False, label='联系人')
    phone = CharField(required=False, label='手机号')
    email = CharField(required=False, label='邮箱')
    evaluate = CharField(required=False, label='客户评价')
    address = CharField(required=False, label='地址')
    remark = CharField(required=False, label='备注')
    class Meta:
        model = Client
        fields = ['number', 'name', 'profile','cooperation_attribute',
                  'cooperation_types','contact', 'phone', 'email',
                  'evaluate','address', 'remark']


class SupplierManufactorImportSerializer(BaseSerializer):
    # company = IntegerField(label='所属公司')
    number = CharField(label='厂家编号(必填唯一)')
    name = CharField(label='厂家名称(必填唯一)')
    accounting_period = IntegerField(label='账期(月)')
    credit_limit = FloatField(label='信用额度(万元)')
    product_specialty = JSONField(required=False, label='产品覆盖专业，格式：[1,2]')
    contact = CharField(required=False, label='联系人')
    phone = CharField(required=False, label='手机号')
    email = CharField(required=False, label='邮箱')
    remark = CharField(required=False, label='备注')
    class Meta:
        model = SupplierManufactor
        fields = ['number', 'name', 'accounting_period','credit_limit',
                  'product_specialty','contact', 'phone', 'email',
                   'remark']

class SupplierIntegratorImportSerializer(BaseSerializer):
    number = CharField(label='集成商编号(必填唯一)')
    name = CharField(label='集成商名称(必填唯一)')
    business_scope = CharField(required=False, label='营业范围')
    business_qualification = CharField(required=False,label='营业资质')
    contact = CharField(required=False, label='联系人')
    phone = CharField(required=False, label='手机号')
    email = CharField(required=False, label='邮箱')
    remark = CharField(required=False, label='备注')
    class Meta:
        model = SupplierIntegrator
        fields = ['number', 'name', 'business_scope','business_qualification',
                  'contact', 'phone', 'email', 'remark']


class ManufactorProductImportSerializer(BaseSerializer):
    number = CharField(label='产品编号(必填唯一)')
    name = CharField(label='产品名称')
    product_model = CharField(required=False, label='产品型号')
    product_price = FloatField(required=False,label='产品单价')
    product_specialty = JSONField(required=False, label='产品覆盖专业，格式：[1,2]')
    supplier_manufactor = IntegerField(label='厂家id')
    class Meta:
        model = SupplierIntegrator
        fields = ['number', 'name', 'product_model','product_price',
                  'product_specialty', 'supplier_manufactor']

class ClientExportSerializer(BaseSerializer):

    # class Cooperation_typesSerializer(BaseSerializer):
    #
    #     class Meta:
    #         model = Cooperation_types
    #         fields = ['id', 'name']

    # cooperation_types_list = Cooperation_typesSerializer(
    #     source='cooperation_types.name', many=True, read_only=True, label='合作属性')
    # cooperation_types_list=Cooperation_typesSerializer(source='cooperation_types', read_only=True, label='合作属性')

    # print(cooperation_types_list)
    company_name = CharField(source='company.name', read_only=True, label='公司')

    # company = IntegerField(label='所属公司')
    number = CharField(label='客户编号')
    name = CharField(label='客户名称')
    profile = CharField(required=False, label='客户简介')
    # cooperation_attribute = JSONField(required=False, label='合作方式，格式：[1,2]')
    # cooperation_types = JSONField(required=False, label='合作行业类型，格式：[1,2]')
    contact = CharField(required=False, label='联系人')
    phone = CharField(required=False, label='手机号')
    email = CharField(required=False, label='邮箱')
    address = CharField(required=False, label='地址')
    remark = CharField(required=False, label='备注')
    is_effective = IntegerField(required=False, label='状态(默认: 0，-1=待修改，0=待审核，1=已生效)')
    class Meta:
        model = Client
        fields = [
            'company_name',
            'number', 'name', 'profile',
                  # 'cooperation_attribute','cooperation_types',
                  # 'cooperation_types_list',
                  'contact', 'phone', 'email', 'address', 'remark',
                  'is_effective']


__all__ = [
    'ClientSerializer',
    'SupplierManufactorSerializer',
    'ClientImportExportSerializer',
    'ClientExportSerializer',
    'CheckFlowSerializer',
    'SupplierManufactorImportSerializer',
    'SupplierIntegratorSerializer',
    'SupplierIntegratorImportSerializer',
    'IntegratorPdfSerializer',
    'ManufactorProductSerializer',
    'ManufactorProductImportSerializer',

]